<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDictionarytypes">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="dictionarytypes" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="产品类型" width="220" sortable>
      </el-table-column>
      <el-table-column prop="name" label="产品名称" width="220" sortable>
      </el-table-column>

      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="showInner(scope.$index, scope.row)" >详情</el-button>
<!--          <el-button @click="table = true" type="primary" style="margin-left: 16px;" size="small">详情</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>


    <el-dialog :title="title" :visible.sync="dictionarytypeFormVisible" :close-on-click-modal="false">
      <el-form :model="dictionarytypeForm" label-width="80px" :rules="dictionarytypeFormRules" ref="dictionarytypeForm">
        <!--prop="name"  申明表单中有一个属性name-->
        <el-form-item label="产品类型" prop="sn">
          <el-input v-model="dictionarytypeForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="dictionarytypeForm.name" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dictionarytypeFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="dictionarytypeSubmit" >提交</el-button>
      </div>
    </el-dialog>

<!--  ++++++++++抽屉内容++++++++++  -->
    <div>


<!--      <el-drawer
          title="我是标题"
          :visible.sync="drawer"
          :with-header="false">
        <span>我来啦!</span>
      </el-drawer>
      <el-button type="text" @click="table = true">打开嵌套表格的 Drawer</el-button>-->

      <el-drawer
          title="产品详情"
          :visible.sync="table"
          direction="rtl"
          size="50%">
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <el-form :inline="true" :model="filtersDetail">
            <el-form-item>
              <el-input v-model="filtersDetail.keywordDetail" placeholder="关键字"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-on:click="handleDicType">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAddDetail">新增</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="dictionarydetails" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" width="20">
          </el-table-column>
          <el-table-column prop="name" label="分类名称" width="120" sortable>
          </el-table-column>
<!--          <el-table-column prop="types.name" label="分类类型" width="120" sortable>
          </el-table-column>-->

          <el-table-column label="操作" >
            <template scope="scope">
              <el-button size="small" @click="handleEditDetail(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelDetail(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
          <el-button type="danger" :disabled="this.sels.length===0">批量删除</el-button>
          <el-pagination layout="prev, pager, next"
                         @current-change="handleCurrentChangeDetail"
                         :page-size="pageSizeDetail"
                         :current-page="currentPageDetail"
                         :total="totalDetail"
                         style="float:right;">
          </el-pagination>
        </el-col>
      </el-drawer>
    </div>

<!--     模态框-->
    <el-dialog :title="titleDeatil" :visible.sync="dictionarydetailFormVisible" :close-on-click-modal="false">
      <el-form :model="dictionarydetailForm" label-width="80px" :rules="dictionarydetailFormRules" ref="dictionarydetailForm">
        <!--prop="name"  申明表单中有一个属性name-->
<!--        <el-form-item label="产品类型" >
          <el-input v-model="dictionarydetailForm.nameType" auto-complete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="产品名称">
          <el-input v-model="dictionarydetailForm.name" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dictionaryDetailFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="dictionarydetailSubmit" >提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>
<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getDictionarytypeListPage, removeDictionarytype, batchRemoveDictionarytype, dictionarytypeDictionarytype, addDictionarytype } from '../../api/api'

export default {
  data() {

    return {
      listLoading:false,
      filters: {
        keyword: ''
      },
      filtersDetail: {
        typesId:null,
        keywordDetail: ''
      },
      dictionarytypes: [],
      dictionarydetails:[],

      total: 0,
      pageSize:2,
      currentPage: 1,
      title:'',
      titleDeatil:'',
      sels: [],//列表选中行
      dictionarytypeForm: {
        id: null,
        name: "",
        sn: "",
      },
      dictionarytypeFormVisible: false,//编辑界面是否显示
      dictionarytypeLoading: false,
      dictionarytypeFormRules: {
        sn: [
          { required: true, message: '请输入该字段', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入该字段', trigger: 'blur' }
        ],


      },

      //  ++++++抽屉++++++
      dictionarydetailFormVisible: false,//编辑界面是否显示
      dictionarydetailLoading: false,
      dictionarydetailFormRules: {
        name: [
          { required: true, message: '请输入该字段', trigger: 'blur' }
        ],
      },

      //  ++++++字典详情的数据++++++
      totalDetail:null,
      pageSizeDetail:5,
      currentPageDetail: 1,
      titleDetail:null,

      dictionarydetailForm: {
        id: null,
        types: null,
        name: null,
      },

      drawer: false,
      table: false,
      dialog: false,
      loading: false,

      dictionaryTypes:[],
      dictionaryDetailLoading:true,

      detailId:null
    }
  },
		methods: {
/*			//状态显示转换
			formatSex: function (row, column) {
				return row.state == 0 ? '启用' : row.state == -1 ? '禁用' : '未知';
			},*/
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDictionarytypes();
			},
      handleCurrentChangeDetail(val) {
        this.currentPageDetail = val;
        this.getDictionarytypes();
      },

			//获取字典类型列表 分页 + 高级 start------------------
			getDictionarytypes() {
				let para = {
          currentPage: this.currentPage,
          keyword: this.filters.keyword,
          pageSize:this.pageSize
				};
				//this.listLoading = true;
        this.$http.post("/type",para)
        .then(result=>{
          result = result.data
          this.dictionarytypes = result.rows
          console.log(this.dictionarytypes)
          this.total = result.total
        }).catch(result=>{
          alert("ERROR")
        })

			},
      // ----------------------------end

			//删除--------------------------
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id }; // restful风格需要对象
          this.$http.delete("/type/"+row.id)
              .then(result=>{
                this.listLoading = false; // 关闭忙
                this.dictionarytypeLoading = false;
                result = result.data
                this.dictionarytypes = result.rows
                if (result.success){
                  this.$message({ // 弹窗
                    message: '删除成功',
                    type: 'success'
                  });
                }else {
                  this.$message({ // 弹窗
                    message: '删除失败',
                    type: 'error'
                  });
                }
              this.currentPage = 1 // 定位到第一页
              this.getDictionarytypes() // 刷新列表
          })
              .catch(result=>{ // 系统错误的情况，和后端没有关系
                this.listLoading = false;
                console.log(result.message)
          })

        }).catch(result=>{
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '取消删除',
            type: 'error'
          });
          //取消删除需要重新刷新
          this.currentPage = 1;
          this.handleDicType();
        })

      },

      // ----------------------------end
			//显示编辑界面
      handleEdit: function (index, row) {
			  this.title='编辑'
				this.dictionarytypeFormVisible = true;
				this.dictionarytypeForm = Object.assign({}, row); // 编辑回显
        let dirPath = row.dirPath // /2/7

        if (dirPath){
          let arr = dirPath.split("/"); // String数组 Array[ "", "2", "7" ]
          let parent = [];
          for (let i = 1; i < arr.length-1; i++) { // 由于dirPath 只需要父级dirPath 来回显上级字典类型
            parent.push(parseInt(arr[i])) // parent:Array [ 2 ]
          }
          this.dictionarytypeForm.parent = parent
        }


			},
			//显示新增界面
			handleAdd: function () {
        this.title='新增'
				this.dictionarytypeFormVisible = true;
				this.dictionarytypeForm = { // 清空数据

            id: null,
            name: "",
            sn: "",

				};
			},


			//新增或修改
      dictionarytypeSubmit: function () {
				this.$refs.dictionarytypeForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.dictionarytypeLoading  = true;
							let para = Object.assign({}, this.dictionarytypeForm);// 克隆
              // 我们添加的时候报错：JSON parse error ，看请求可知para.parent是一个数组，把祖宗的id也获取了[2,5] ，但我们只需要上一级的id，处理数据
              if(para.parent) { // [2,5]数组 --父级有值
                let parent = para.parent
                let pid =  parent[parent.length-1] // 根据下标取值 [2,5]
                para.parent = {"id": pid} // 重新赋值包装为json格式
              }
              this.$http.put("/type",para)
                  .then(result=>{
                    this.dictionarytypeFormVisible = false;
                    this.dictionarytypeLoading = false;
                    result = result.data
                    console.log(result)
                    if (result.success){
                      this.$message({ // 弹窗
                        message: '操作成功',
                        type: 'success'
                      });
                    }else {
                      this.$message({ // 弹窗
                        message: '操作失败',
                        type: 'error'
                      });
                    }
                    this.currentPage = 1 // 定位到第一页
                    this.getDictionarytypes() // 刷新列表
                  })
                  .catch(result=>{ // 系统错误的情况，和后端没有关系
                    this.dictionarytypeLoading  = false;
                    this.listLoading = false;
                    console.log(result.message)
                  })
						}).catch(result=>{
              this.dictionarytypeLoading  = false;
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: '取消操作',
                type: 'error'
              });
              //取消删除需要重新刷新
              this.currentPage = 1;
              this.getDictionarytypes();
            })
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},



      // -----------------------------内层------------------------------
      showInner(index,row){
			  this.table = true
        this.typesId = row.id
        this.handleDicType();
      },
      // 根据id获取抽屉内对应信息
      handleDicType() {
        let para = {
          "typesId": this.typesId,
          "currentPage": this.currentPageDetail,
          "keyword": this.filtersDetail.keywordDetail,
          "pageSize": this.pageSizeDetail
        };
        console.log("typesId"+para.typesId)
      //this.listLoading = true;
      this.$http.post("/detail",para)
          .then(result=>{
            result = result.data
            this.dictionarydetails = result.rows

            this.totalDetail = result.total
          }).catch(result=>{
            alert("ERROR")
          })

      },
      Reflush(){
        let para = {
          "types_id":this.detailId,
          "currentPage": this.currentPageDetail,
          "keyword": this.filtersDetail.keywordDetail,
          "pageSize":this.pageSizeDetail
        };
        //this.listLoading = true;
        this.$http.post("/detail",para)
            .then(result=>{
              result = result.data
              this.dictionarydetails = result.rows
              console.log(this.dictionarydetails)
              this.totalDetail = result.total
            }).catch(result=>{
          alert("ERROR")
        })

      },
  getDictionaryTypes(){
    this.$http.get("/type").then((res=>{
      //产品名写入内层抽屉中
      this.dictionaryTypes = res.data
       console.debug(res.data)
    }))
  },
      // 抽屉提交表单
  dictionarydetailSubmit: function () {
    this.$refs.dictionarydetailForm.validate((valid) => {
      if (valid) {
        this.dictionarydetailForm.types = {"id":this.detailId}
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          let para = Object.assign({}, this.dictionarydetailForm) ;// 克隆
          console.log(para)
          this.$http.put("/detail",para,)
              .then(result=>{
                this.dictionarydetailFormVisible = false;
                result = result.data
                console.log(result)
                if (result.success){
                  this.$message({ // 弹窗
                    message: '操作成功',
                    type: 'success',
                  });
                  this.Reflush()
                }else {
                  this.$message({ // 弹窗
                    message: '操作失败',
                    type: 'error'
                  });
                }
                this.currentPageDetail = 1 // 定位到第一页
                this.handleDicType() // 刷新列表
              })
              .catch(result=>{ // 系统错误的情况，和后端没有关系
                console.log(result.message)
              })
        }).catch(result=>{
          //NProgress.done();
          this.$message({
            message: '取消操作',
            type: 'error'
          });
          //取消删除需要重新刷新
          this.currentPage = 1;
          this.handleDicType();
        })
      }
    });
  },

      //删除--------------------------
      handleDelDetail: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'}).then(() => {
          //NProgress.start();
          let para = { id: row.id }; // restful风格需要对象
          this.$http.delete("/detail/"+row.id)
              .then(result=>{
                this.listLoading = false; // 关闭忙
                this.dictionarydetailLoading = false;
                result = result.data
                console.log(result)
                this.dictionarydetails = result.rows
                console.log(this.dictionarydetails)
                if (result.success){
                  this.$message({ // 弹窗
                    message: '删除成功',
                    type: 'success'
                  });
                  this.currentPageDetail = 1 // 定位到第一页
                  this.Reflush() // 刷新列表
                }else {
                  this.$message({ // 弹窗
                    message: '删除失败',
                    type: 'error'
                  });
                }
                this.currentPageDetail = 1 // 定位到第一页
                this.handleDicType() // 刷新列表
              })
              .catch(result=>{ // 系统错误的情况，和后端没有关系
                this.listLoading = false;
                console.log(result.message)
              })

        }).catch(result=>{
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '取消删除',
            type: 'error'
          });
          //取消删除需要重新刷新
          this.currentPageDetail = 1;
          this.handleDicType();
        })

      },
  // 抽屉
  handleAddDetail(){
    this.titleDetail='新增详情'
    this.dictionarydetailFormVisible = true;
    this.dictionarydetailForm = { // 清空数据

      id: null,
      name: "",
      types: "",

    };

  }, handleEditDetail: function (index, row) {
    this.titleDetail='编辑详情'
    this.dictionarydetailFormVisible = true;
    this.dictionarydetailForm = Object.assign({}, row); // 编辑回显


  },
    },
		mounted() {
			this.getDictionarytypes();


		}
	}

</script>

<style scoped>

</style>